//
//  SLAddLockScanVC.m
//  SlockApp
//
//  Created by 凯朱 on 2024/7/16.
//

#import "SLAddLockScanVC.h"
#import "VIGRadarView.h"
#import "SLAddLockListCell.h"
#import "SLSetLockNameVC.h"

static  NSString *const kCellId = @"SLAddLockListCell";
@interface SLAddLockScanVC ()<UITableViewDelegate,UITableViewDataSource>{
    BOOL _isBridge;
    NSString *_followId;
}
@property (nonatomic, strong)NSMutableArray *dataArray;
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)VIGRadarView *radarView;
@property (nonatomic, strong)NSArray *productList;/**/
@property (nonatomic, strong)NSTimer *timer;
@property (nonatomic, assign)NSInteger time;
@end

@implementation SLAddLockScanVC

- (void)viewDidLoad {
    [super viewDidLoad];
    _isBridge = _type != 1;
    _productList = [UserManager getProductList];
    [[SLBluetoothManager sharedManager] disConnectPeripheral];
    [self setUpSubViews];
}

-(void)backBtnClicked{
    [super backBtnClicked];
    if (_isBridgeAddLock) {
        [self destoryTimer];
    }else{
        [[SLBluetoothManager sharedManager] stopSearchDevice];
    }
}

-(void)destoryTimer{
    if (self.timer && self.timer.isValid) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

-(void)setUpSubViews{
    if (_isBridge) {
        self.title = kLocalString(@"Add bridge");
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(becomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self startScan];
        });
    } else {
        self.title = kLocalString(@"Add new device");
        [ZCTool showAwakeTipAlert:^{
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(becomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
            [self startScan];
        }];
    }
    _tipLbl.text = kLocalString(@"Scanning...");
    _tipLbl1.text = kLocalString(@"Your lock should be nearby.");
    _tipLbl2.text = kLocalString(@"Touch the fingerprint pad once to awake the padlock.");
    _iconLabel1.layer.cornerRadius = 3;
    _iconLabel1.layer.masksToBounds = YES;
    _iconLabel2.layer.cornerRadius = 3;
    _iconLabel2.layer.masksToBounds = YES;
    
    _failTipLbl1.text = kLocalString(@"May be you are too far from your lock.");
    _failDescLbl1.text = kLocalString(@"First, make sure Bluetooth is enabled on your phone. Setup works best when your phone is a few feet from your lock.");
    _failIcon1.layer.cornerRadius = 3;
    _failIcon1.layer.masksToBounds = YES;
    
    _failTipLbl2.text = kLocalString(@"Try to touch the fingerprint sensor.");
    _failDescLbl2.text = kLocalString(@"The lock may enter sleep mode after a period of inactivity. Touch the fingerprint sensor to wake it up.");
    _failIcon2.layer.cornerRadius = 3;
    _failIcon2.layer.masksToBounds = YES;
    
    _failTipLbl3.text = kLocalString(@"Check your app permissions.");
    _failDescLbl3.text = kLocalString(@"Bluetooth and location permissions are required to search for and connect to your device. Please enable them in settings.\nGo to Home > Pererences > Permissions > Location, set Bluetooth to \"Allowed\".");
    _failIcon3.layer.cornerRadius = 3;
    _failIcon3.layer.masksToBounds = YES;
    
    _failTipLbl4.text = kLocalString(@"The lock has been paired already.");
    _failDescLbl4.text = kLocalString(@"Only one HEXFORCE account can own a lock at a time. You can reset the lock to enable it's pairing mode.");
    _failIcon4.layer.cornerRadius = 3;
    _failIcon4.layer.masksToBounds = YES;
    _bgView2.hidden = YES;
    
    [_supBtn setLineTextWith:kLocalString(@"Go for support")];
    _supBtn.hidden = NO;
    _supBtnHeight.constant = 0;
    _sureBtn.btnStyle = 1;
    
    
    [_sureBtn setTitle:kLocalString(@"Stop scanning") forState:UIControlStateNormal];
    [self.scanBgView addSubview:self.radarView];
    [self.radarView start];
    [self.tableBgView addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.offset(0);
    }];
    _tableBgView.hidden = YES;
    
}

-(void)becomeActive{
    [self.radarView start];
}

- (IBAction)sureAction:(ZKBaseButton *)sender {
    if ([_sureBtn.titleLabel.text isEqualToString:kLocalString(@"Ok, I'll try again")] 
        || [_sureBtn.titleLabel.text isEqualToString:kLocalString(@"Scan again")]) {
        [self startScan];
        
    }else{
        if (_isBridgeAddLock) {
            [self stopBridgeSearchDevices];
        }else{
            [self stopScanDevices];
        }
    }
}

//app停止扫描智锁设备
-(void)stopScanDevices{
    self.radarView.hidden = YES;
    [self.radarView stop];
    [[SLBluetoothManager sharedManager] stopSearchDevice];
    [_sureBtn setTitle:kLocalString(@"Scan again") forState:UIControlStateNormal];
}

-(void)startScan{
    kWeakSelf(self);
    _tipBgViewHeight.constant = 80;
    _bgView2.hidden = YES;
    _supBtn.hidden = YES;
    _supBtnHeight.constant = 0;
    _tableBgView.hidden = YES;
    _tipBgView.hidden = NO;
    _scanBgView.hidden = NO;
    _radarView.hidden = NO;
    _tipLbl.text = kLocalString(@"Scanning...");
    [_radarView start];
    [_sureBtn setTitle:kLocalString(@"Stop scanning") forState:UIControlStateNormal];
    
    [self.dataArray removeAllObjects];
    [_tableView reloadData];
    if (_isBridgeAddLock) {//网关扫描周围设备
        NSDictionary *params = @{@"deviceNo":kCurClickDevice.deviceNo,
                                 @"scanMode":@"1",
                                 @"scanTimes":@"30"};
        [ZKHttpManager postWithPath:@"/msl_user/scanDevice" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
            [ZCTool hideLoadingOnKeyWindow];
            if (!isSuccessed) {
                kShowToast(message);
                return;
            }
            self->_followId = result[@"result"];
            //开始每隔2s获取一次设备信息
            if (!weakself.timer) {
                weakself.time = 0;
                weakself.timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(checkScanDeviceInfo) userInfo:nil repeats:YES];
                [weakself.timer fire];
            }
        }];
    }
    else{//app扫描周围设备
        [SLBluetoothManager sharedManager].autoConnectDeviceNo = @"";
        [[SLBluetoothManager sharedManager] startSearchDevice:_isBridge finish:^(BOOL isSuccess, CBPeripheral *peripheral,id data, NSString *errorMsg) {
            //搜索到设备
            [self hanldeScanData:data isSuccess:isSuccess peripheral:peripheral];
        }];
    }
}

-(void)checkScanDeviceInfo{
    kWeakSelf(self);
    _time += 3;
    if (weakself.time >= 30) {
        [self stopBridgeSearchDevices];
        //10s未扫到任何设备
        if (weakself.dataArray.count == 0) {
            [self hanldeScanData:nil isSuccess:NO peripheral:nil];
        }
    }
    NSString *url = [NSString stringWithFormat:@"/msl_user/scanDeviceQuery/%@",_followId];
    [ZKHttpManager getWithPath:url params:@{} finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        if (!isSuccessed) {
            return;
        }
        NSArray *deviceList = result[@"result"][@"data"];
        if (deviceList.count > 0) {
            [deviceList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                NSMutableDictionary *data = [NSMutableDictionary new];
                [data setObject:kSTRING(obj[@"license"]) forKey:@"deviceNo"];
                [data setObject:kSTRING(obj[@"productID"]) forKey:@"productId"];
                [data setObject:obj forKey:@"bridgeScanInfo"];
                [self hanldeScanData:data isSuccess:YES peripheral:nil];
            }];
        }
    }];
}

//网关停止扫描设备
-(void)stopBridgeSearchDevices{
    self.radarView.hidden = YES;
    [self.radarView stop];
    [self destoryTimer];
    NSDictionary *params = @{@"deviceNo":kCurClickDevice.deviceNo,
                             @"scanMode":@"2",
                             @"scanTimes":@"30"};
    [ZKHttpManager postWithPath:@"/msl_user/scanDevice" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        
    }];
    [_sureBtn setTitle:kLocalString(@"Scan again") forState:UIControlStateNormal];
}

-(void)hanldeScanData:(NSDictionary *)data isSuccess:(BOOL)isSuccess peripheral:(CBPeripheral *)peripheral{
    kWeakSelf(self);
    if (isSuccess) {
        __block BOOL isHaveDevice = NO;
        NSString *deviceNo = kSTRING(data[@"deviceNo"]);
        NSString *isBindFlag = kSTRING(data[@"isBindFlag"]);
        
        //已绑定的设备不显示
        if ([isBindFlag isEqualToString:@"1"] && ![ZCTool isOpenDebugModel]){
            return;
        }
            
        [weakself.dataArray enumerateObjectsUsingBlock:^(SLLockModel *device, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([device.deviceNo isEqualToString:deviceNo]) {
                isHaveDevice = YES;
                *stop = YES;
            }
        }];
        if (!isHaveDevice) {
            SLLockModel *model = [[SLLockModel alloc] init];
            if (peripheral) model.deviceName = peripheral.name;
            model.productId = kSTRING(data[@"productId"]);
            model.isBind = [isBindFlag boolValue];
            [self->_productList enumerateObjectsUsingBlock:^(SLProductModel *item, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([item.productNo isEqualToString:model.productId]) {
                    model.productName = item.productName;
                    *stop = YES;
                }
            }];
            model.deviceNo = deviceNo;
            model.major = [deviceNo substringWithRange:NSMakeRange(0, 2)];
            model.minor = [deviceNo substringWithRange:NSMakeRange(deviceNo.length-2, 2)];
            if ([[data allKeys] containsObject:@"bridgeScanInfo"]) {
                model.bridgeScanInfo = data[@"bridgeScanInfo"];
            }
            if (peripheral) model.peripheral = peripheral;
            model.deviceCategory = self->_isBridge ? @"2" : @"1";
            [weakself.dataArray addObject:model];
        }
        [self searchSuccess];
        [weakself.tableView reloadData];
    }else{
        [self searchFaild];
    }
}

-(void)searchSuccess{
    _tipBgViewHeight.constant = 0;
    if (_type == 1) {
        _tipLbl.text = kLocalString(@"Choose a lock or device to add.");
    }else{
        _tipLbl.text = kLocalString(@"Choose the bridge you need to add.");
    }
    _tipBgView.hidden = YES;
    _tableBgView.hidden = NO;
}

-(void)searchFaild{
    _bgView2.hidden = NO;
    _tableBgView.hidden = YES;
    _tipBgView.hidden = YES;
    _scanBgView.hidden = YES;
    _supBtn.hidden = YES;
//    _supBtnHeight.constant = 50;
    _supBtnHeight.constant = 0;
    _tipLbl.text = kLocalString(@"Lock not found.");
    [_radarView stop];
    [_sureBtn setTitle:kLocalString(@"Ok, I'll try again") forState:UIControlStateNormal];
}

-(VIGRadarView *)radarView {
    if (!_radarView) {
        CGRect parentFrame = CGRectMake(0, 0, kScreenWidth, kScreenHeight-80-SafeAreaBottomHeight-SafeAreaTopHeight);
        _radarView = [[VIGRadarView alloc] initWithFrame:CGRectMake(0, 0, parentFrame.size.width, parentFrame.size.height)];
        _radarView.scanSpeed = 0.5;
    }
    return _radarView;
}

- (IBAction)supBtnAction:(id)sender {
    NSString *url = [NSString stringWithFormat:@"%@/index.html#/appsupport/index",URL_web];
    RootWebViewController *webVc = [[RootWebViewController alloc] initWithUrl:url];
    webVc.title = kLocalString(@"Support");
    [self.navigationController pushViewController:webVc animated:YES];
}

#pragma mark - ================<tableViewDataSource>===============
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dataArray.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SLAddLockListCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellId];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    SLLockModel *model = _dataArray[indexPath.section];
    cell.model = model;
    return cell;
}

#pragma mark - ================<UITableViewDelegate>===============
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 100;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 20;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UITableViewHeaderFooterView *headview = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"head"];
    if (!headview) {
        headview = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"head"];
        headview.frame = CGRectMake(0, 0, kScreenWidth, 20);
        headview.contentView.backgroundColor = KClearColor;
    }
    return headview;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UITableViewHeaderFooterView *footerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"foot"];
    if (!footerView) {
        footerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:@"foot"];
        footerView.frame = CGRectMake(0, 0, kScreenWidth, 0.1);
        footerView.contentView.backgroundColor = KClearColor;
    }
    return footerView;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    SLLockModel *model = _dataArray[indexPath.section];
   
    if ([_sureBtn.titleLabel.text isEqualToString:kLocalString(@"Stop scanning")]) {
        [self sureAction:_sureBtn];
    }
    SLSetLockNameVC *vc = [[SLSetLockNameVC alloc] init];
    vc.type = _type;
    vc.isBridgeAddLock = _isBridgeAddLock;
    vc.addLockBlock = _addLockBlock;
    vc.model = model;
    vc.bridgeListVc = _bridgeListVc;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - ================<懒加载>===============
-(UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.estimatedRowHeight = 100;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerNib:[UINib nibWithNibName:kCellId bundle:nil] forCellReuseIdentifier:kCellId];
        _tableView.backgroundColor = KClearColor;
    }
    return _tableView;
}

-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (NSData *)hexadecimalData:(NSString *)str {
    NSMutableData *data = [NSMutableData data];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
    int i = 0;
    while (i < [str length]) {
        byte_chars[0] = [str characterAtIndex:i++];
        byte_chars[1] = [str characterAtIndex:i++];
        whole_byte = strtol(byte_chars, NULL, 16);
        [data appendBytes:&whole_byte length:1];
    }
    return data;
}
@end
